package com.service.attention;

import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.event.attention.AttentionEvent;
import com.event.attention.AttentionEventListener;
import com.google.common.eventbus.EventBus;
import com.mapper.self.AttentionMapper;
import com.mapper.self.CompanyMapper;
import com.pojo.ShAttention;
import com.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Huoyunren on 2016-09-06.
 */
@Service
public class AttentionServiceImpl implements AttentionService {

  @Autowired
  private AttentionMapper attentionMapper;
  @Autowired
  private AttentionEventListener attentionEventListener;

  @Override
  public int saveOrUpdate(String attentionEmail, Integer isAttention) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Object email = request.getSession().getAttribute("email");
    if (email == null) {
      throw BizException.create(Codes.NotLogin);
    }
    if (attentionEmail.equals(email.toString())) {
      throw BizException.create(Codes.SystemDeclare, "不能自己关注自己");
    }
    ShAttention attention = new ShAttention();
    attention.setAttentionEmail(attentionEmail);
    attention.setCreateTime(DateUtils.currentDate());
    attention.setDeleted(isAttention);
    attention.setEmail(email.toString());
    attentionMapper.saveOrUpdate(attention);
    // - 关注通知
    attentionNotify(attentionEmail, email,isAttention);
    return 0;
  }

  // - 关注，邮件提醒。通过eventBus实现业务解耦
  private void attentionNotify(String attentionEmail, Object email, Integer isAttention) {
    EventBus eventBus = new EventBus(AttentionEvent.class.getName());
    eventBus.register(attentionEventListener);
    AttentionEvent attentionEvent = new AttentionEvent();
    attentionEvent.setEmail(email.toString());
    attentionEvent.setAttentionEmail(attentionEmail);
    attentionEvent.setIsAttention(isAttention);
    eventBus.post(attentionEvent);
  }


  @Override
  public Object list(String email, Integer pageNo, Integer pageSize) {
    if (pageNo == null) {
      pageNo = 0;
    }
    if (pageNo > 0) {
      pageNo--;
    }
    return attentionMapper.list(email, pageNo*pageSize, pageSize);
  }
}
